﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using WCBG.ToolsForUnity.Tools;
using UnityEngine.UI;

public class VaccineDragItem : UIDrag3DBase {

    public string _modelPath;
    public string _texturePath;
    Camera _cam;
    GameObject _object;
    Animator _animator;

    public override void InitComponet()
    {
        base.InitComponet();

        _cam = VaccineGameManager.Instance._cam;
        _animator = GetComponentInChildren<Animator>();
        _loopAudioName = HospitalConsts.audio_bingfu_tumo;
    }

    public override void OnBeginDrag(PointerEventData eventData)
    {
        base.OnBeginDrag(eventData);

        VaccineGameManager.Instance.vaccineTreatment._bingdaiObject = _currentDragObject.gameObject;
        //关闭动画
        _animator.enabled = false;
    }

    public override Vector3 Get3DPosition()
    {
        Plane plane = new Plane(_cam.transform.forward * -1, new Vector3(0.5267f, 1f, -0.96f));
        Ray ray = _cam.ScreenPointToRay(Input.mousePosition);
        Debug.DrawRay(ray.origin,ray.direction,Color.red);
        float dis;
        if (plane.Raycast(ray, out dis))
        {
            Vector3 point = ray.GetPoint(dis);
            return point;
        }

        return Vector3.zero;
    }

    protected override void Update()
    {
        if (_onDragging)
        {
            _currentDragObject.position = Vector3.Lerp(_currentDragObject.position, _targetDragObjectPosition, .5f);
        }
    }

    public override void OnDrag(PointerEventData eventData)
    {
        base.OnDrag(eventData);

        Ray ray = _cam.ScreenPointToRay(Input.mousePosition);
        RaycastHit hit;
        if (Physics.Raycast(ray, out hit, Mathf.Infinity, 1 << LayerMask.NameToLayer("Draggable")))
        {
            ActiveLoopAudio(true);
            //注意：这里注意先后次序，因为在OnXiaoZhongUpdate（）中有ActiveLoopAudio(false);的操作。放置被重新打开
            VaccineGameManager.Instance.vaccineTreatment.OnXiaoZhongUpdate();
        }
        else
        {
            ActiveLoopAudio(false);
        }

    }

    public override void OnEndDrag(PointerEventData eventData)
    {
        base.OnEndDrag(eventData);
        ActiveLoopAudio(false);
    }

    public override Transform _currentDragObject
    {
        get
        {
            if (_object == null)
            {
                _object = HospitalResManager.GetActiveObject(HospitalConsts.game_hospital_prefab_stomachache_BasePath, _modelPath);
                HospitalController.Instance.RegistCacheObject(_object);
            }
            Texture2D t2d = Res.LoadTexture2D(FileTools.CombinePath(HospitalConsts.game_hospital_texture_BasePath, _texturePath));
            _object.GetComponentInChildren<Renderer>().material.mainTexture = t2d;
            _object.transform.LookAt(_cam.transform);

            return _object.transform;
        }

        set
        {
            base._currentDragObject = value;
        }
    }



}
